<template>
  <div class="menu-page">
    <n-space class="menu-container" :vertical="true">
      <n-form inline label-width="auto" :model="formValue" ref="formRef">
        <n-form-item label="菜单名称" path="name">
          <n-input v-model:value="formValue.name" placeholder="输入菜单名称" />
        </n-form-item>
        <n-form-item>
          <n-button @click="queryForm" attr-type="button">查询</n-button>
        </n-form-item>
        <n-form-item>
          <n-button @click="insertRow()" attr-type="button">添加根菜单</n-button>
        </n-form-item>
      </n-form>
      <n-data-table class="menu-table" :columns="columns" :data="data" :pagination="pagination" />
    </n-space>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, ref } from "vue"
import { NForm, NFormItem, NInput, NButton, NSpace, NDataTable, useDialog, useMessage } from "naive-ui"
import { useRouter } from "vue-router"
import { renderTableCols } from "@/composition/table"

const router = useRouter()
const dialog = useDialog()
const message = useMessage()
const api = getCurrentInstance()?.appContext.config.globalProperties.$api

const formRef = ref()
const formValue = ref({
  name: "",
})

const data = ref([])

onMounted(async () => {
  await queryForm()
})

const queryForm = async () => {
  let response: any = await api.menuFullList()
  data.value = response.data.data
}

const insertRow = (parentId?: number) => {
  router.push({ path: "/menu/form" })
}

const tableColMeta = [
  { title: "ID", key: "id" },
  { title: "菜单名称", key: "name" },
  { title: "菜单路径", key: "path" },
  { title: "菜单状态", key: "status" },
  { title: "创建时间", key: "createTime" },
  { title: "修改时间", key: "updateTime" },
  { title: "操作", key: "#" },
]

const optActions = [
  {
    name: "详情",
    action: (row: any) => router.push({ path: "/menu/form", query: { id: row.id, isView: 1 } }),
  },
  {
    name: "修改",
    action: (row: any) => router.push({ path: "/menu/form", query: { id: row.id } }),
  },
  {
    name: "删除",
    action: (row: any) => {
      dialog.warning({
        title: "警告",
        content: "你确定删除这条记录吗？",
        positiveText: "删除",
        negativeText: "取消",
        onPositiveClick: async () => {
          let response: any = await api.removeMenu({ id: row.id })
          if (response.data.successful) {
            message.success("删除成功！")
            await queryForm()
          }
        },
      })
    },
  },
  {
    name: "添加子菜单",
    action: (row: any) => router.push({ path: "/menu/form", query: { pId: row.id } }),
  },
]

const columns = ref(renderTableCols(tableColMeta, optActions))

const pagination = {
  pageSize: 10,
}
</script>

<style lang="less" scoped>
.menu-page {
  height: 100%;

  .menu-container {
    padding: 10px 20px;
  }
}
</style>
